//
//  工程名称:XJL_WeChat
//  文件名称:XJLWeChatViewController.m
//
//  创建者  :Created by 许佳莉
//  创建时间:on 16/8/1.
//  版权   :  Copyright © 2016年 Xujiali. All rights reserved.
//

#import "XJLWeChatViewController.h"
#import "XHPopMenu.h"
#import "XJLAddViewController.h"
#import <QRCodeReaderViewController.h>
#import "XJLConversationCell.h"
#import "XJLChatController.h"

@interface XJLWeChatViewController()<EMChatManagerDelegate>

/** PopView*/
@property(nonatomic,strong) XHPopMenu *popView;
/**
 * 与好友的会话列表
 */
@property (nonatomic, strong) NSMutableArray *conversationsM;

@end

@implementation XJLWeChatViewController

-(NSMutableArray *)conversationsM{
    if (_conversationsM == nil) {
        _conversationsM = [NSMutableArray array];
    }
    return _conversationsM;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    
    //    三.网络断了,不稳定,如果网络又通,要重新连接服务器
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    //添加一个加号
    UIBarButtonItem *plusBtnItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(plusAction:)];
    self.navigationItem.rightBarButtonItem = plusBtnItem;
    
    //加载之前的会话记录
    NSArray *conversations = [[EaseMob sharedInstance].chatManager loadAllConversationsFromDatabaseWithAppend2Chat:YES];
    [self.conversationsM addObjectsFromArray:conversations];
    
    [self.tableView reloadData];
}

-(void)plusAction:(id)sender{
    //创建一个Pop
    if (!self.popView) {
        XHPopMenuItem *item1 = [[XHPopMenuItem alloc]initWithImage:[UIImage imageNamed:@"contacts_add_newmessage"] title:@"新聊天室"];
        XHPopMenuItem *item2 = [[XHPopMenuItem alloc] initWithImage:[UIImage imageNamed:@"contacts_add_newmessage"] title:@"新增好友"];
        XHPopMenuItem *item3 = [[XHPopMenuItem alloc] initWithImage:[UIImage imageNamed:@"contacts_add_newmessage"] title:@"扫一扫"];
        XHPopMenuItem *item4 = [[XHPopMenuItem alloc] initWithImage:[UIImage imageNamed:@"contacts_add_newmessage"] title:@"付款"];
        self.popView = [[XHPopMenu alloc]initWithMenus:@[item1,item2,item3,item4]];
        
        //监听点击
        @weakify(self)
        self.popView.popMenuDidSlectedCompled = ^(NSInteger index, XHPopMenuItem *menuItem){
            @strongify(self)
            if (index == 1) {//进入添加好友界面
                XJLAddViewController *addVc = [UIStoryboard storyboardWithName:@"XJLAddViewController" bundle:nil].instantiateInitialViewController;
                addVc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:addVc animated:YES];
            }else if(index == 2){//弹出扫描控制器
                [self openScanQrcodeVc];
            }
        };
    }
    //展现
    [self.popView showMenuAtPoint:CGPointMake(0, 0)];
}

-(void)openScanQrcodeVc{

    // Create the reader object
    QRCodeReader *reader = [QRCodeReader readerWithMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    
    // Instantiate the view controller
    QRCodeReaderViewController *vc = [QRCodeReaderViewController readerWithCancelButtonTitle:@"Cancel" codeReader:reader startScanningAtLoad:YES showSwitchCameraButton:YES showTorchButton:YES];
    
    // Set the presentation style
    vc.modalPresentationStyle = UIModalPresentationFormSheet;
    
    // Define the delegate receiver
//    vc.delegate = self;
    
    // Or use blocks
    @weakify(self)
    [reader setCompletionWithBlock:^(NSString *resultAsString) {
        NSLog(@"%@", resultAsString);
        @strongify(self)
        if (resultAsString.length > 0) {
            [vc stopScanning];
            [[EaseMob sharedInstance].chatManager addBuddy:resultAsString message:@"你好，我是你同学！" error:nil];
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }];
    
    [self presentViewController:vc animated:YES completion:nil];
    
}

#pragma mark 监听网络状态
-(void)didConnectionStateChanged:(EMConnectionState)connectionState{
    if (connectionState == eEMConnectionDisconnected) {
        self.navigationItem.title = @"网络未连接";
        XJLLog(@"未连接");
    }else{
        self.navigationItem.title = @"网络恢复";
        XJLLog(@"网络恢复");
    }
}

/*!
 @method
 @brief 将要发起自动重连操作时发送该回调
 @discussion
 @result
 */
- (void)willAutoReconnect{
    self.navigationItem.title = @"正在连接...";
    XJLLog(@"正在连接");
}

/*!
 @method
 @brief 自动重连操作完成后的回调（成功的话，error为nil，失败的话，查看error的错误信息）
 @discussion
 @result
 */
- (void)didAutoReconnectFinishedWithError:(NSError *)error{
    if (!error) {
        self.navigationItem.title = @"连接成功";
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //更改回标题
            self.navigationItem.title = @"WeChat";
        });
        XJLLog(@"连接成功");
    }
}

#pragma mark 曾经会话的列表
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    XJLLog(@"%ld",self.conversationsM.count);
    return self.conversationsM.count;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"ConversationCell";

    XJLConversationCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[XJLConversationCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    
    cell.conversation = self.conversationsM[indexPath.row];
//    cell.textLabel.text = @"你好";
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 66;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //获取会话对象
    EMConversation *conversation = self.conversationsM[indexPath.row];
    XJLChatController *chatVc = [[XJLChatController alloc]initWithConversationChatter:conversation.chatter conversationType:conversation.conversationType];
    chatVc.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:chatVc animated:YES];
    
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    EMConversation *conversation = self.conversationsM[indexPath.row];
    [[EaseMob sharedInstance].chatManager removeConversationByChatter:conversation.chatter deleteMessages:YES append2Chat:YES];
    
}


#pragma mark 会话列表更新回调
-(void)didUpdateConversationList:(NSArray *)conversationList{
    
    [self.conversationsM removeAllObjects];
    [self.conversationsM addObjectsFromArray:conversationList];
    [self.tableView reloadData];
    
    [self showTotleUnreadCount];
}

-(void)showTotleUnreadCount{
    NSInteger totalUnreadCount = 0;
    for (EMConversation *conversation in self.conversationsM) {
        totalUnreadCount += [conversation unreadMessagesCount];
    }
    
    if (totalUnreadCount) {
        self.navigationController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%zd",totalUnreadCount];
    }
}

@end
